//! Nacos客户端基本使用示例

use nacos_client::{NacosClient, ClientConfig, ServiceInstance};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // 初始化日志
    tracing_subscriber::fmt::init();

    // 创建客户端配置
    let config = ClientConfig::new("127.0.0.1:8848")
        .with_namespace("public")
        .with_timeout(3000, 5000)
        .with_retry(3, 1000);

    // 创建Nacos客户端
    let client = Arc::new(NacosClient::new(config).await?);

    println!("=== Nacos客户端基本使用示例 ===\n");

    // 1. 命名服务示例
    println!("1. 命名服务示例:");
    let naming_client = client.naming_client();

    // 注册服务实例
    let service_name = "example-service";
    let instance = ServiceInstance {
        ip: "127.0.0.1".to_string(),
        port: 8080,
        weight: 1.0,
        healthy: true,
        enabled: true,
        ephemeral: true,
        cluster_name: "default".to_string(),
        service_name: service_name.to_string(),
        namespace: "public".to_string(),
        metadata: {
            let mut map = HashMap::new();
            map.insert("version".to_string(), "1.0".to_string());
            map.insert("environment".to_string(), "development".to_string());
            map
        },
    };

    println!("注册服务实例: {}:8080", instance.ip);
    naming_client.register_instance(service_name, instance.clone()).await?;

    // 等待服务注册
    sleep(Duration::from_millis(500)).await;

    // 发现服务实例
    println!("发现服务实例:");
    let instances = naming_client.get_instances(service_name, true).await?;
    for instance in instances {
        println!("  {}:{} (weight: {}, healthy: {})",
            instance.ip, instance.port, instance.weight, instance.healthy);
    }

    // 2. 配置服务示例
    println!("\n2. 配置服务示例:");
    let config_client = client.config_client("public", "DEFAULT_GROUP");

    let data_id = "example-config";
    let group = "DEFAULT_GROUP";
    let content = r#"
        server:
          port: 8080
          address: 127.0.0.1
        
        database:
          url: jdbc:mysql://localhost:3306/test
          username: root
          password: password
    "#;

    // 发布配置
    println!("发布配置: {}:{}", data_id, group);
    config_client.publish_config(data_id, group, content).await?;

    // 等待配置发布
    sleep(Duration::from_millis(500)).await;

    // 获取配置
    println!("获取配置:");
    let retrieved_content = config_client.get_config(data_id, group).await?;
    println!("配置内容:\n{}", retrieved_content);

    // 3. 缓存功能示例
    println!("\n3. 缓存功能示例:");
    let cached_content = config_client.get_config_cached(data_id, group).await?;
    println!("缓存获取配置长度: {} 字符", cached_content.len());

    // 4. 批量操作示例
    println!("\n4. 批量操作示例:");
    let configs = vec!["config-1", "config-2", "config-3"];
    
    // 批量发布配置
    for config_name in &configs {
        config_client.publish_config(
            config_name,
            "example-group",
            &format!("content for {}", config_name)
        ).await?;
    }

    // 批量获取配置
    let results = config_client.batch_get_config(
        &configs.iter().map(|s| *s).collect::<Vec<&str>>(),
        "example-group"
    ).await?;

    println!("批量获取配置结果:");
    for (key, value) in results {
        println!("  {}: {}", key, value);
    }

    // 5. 监听器示例
    println!("\n5. 监听器示例:");
    
    // 创建监听器
    struct ExampleConfigListener;
    
    #[async_trait::async_trait]
    impl nacos_client::ConfigListener for ExampleConfigListener {
        async fn on_config_changed(&self, data_id: &str, group: &str, content: &str) {
            println!("配置变更通知: {}:{}, 新内容长度: {}", data_id, group, content.len());
        }

        async fn on_config_added(&self, data_id: &str, group: &str, content: &str) {
            println!("配置新增通知: {}:{}, 内容长度: {}", data_id, group, content.len());
        }

        async fn on_config_removed(&self, data_id: &str, group: &str) {
            println!("配置删除通知: {}:{}", data_id, group);
        }
    }

    let listener = Box::new(ExampleConfigListener);
    config_client.add_listener("example-config", "DEFAULT_GROUP", listener).await?;

    // 更新配置触发监听器
    config_client.publish_config(data_id, group, "updated content").await?;
    sleep(Duration::from_millis(200)).await;

    // 6. 健康检查
    println!("\n6. 健康检查:");
    let is_healthy = client.health_check().await?;
    println!("服务器健康状态: {}", if is_healthy { "健康" } else { "不健康" });

    // 7. 清理示例数据
    println!("\n7. 清理示例数据:");
    
    // 删除配置
    config_client.remove_config(data_id, group).await?;
    for config_name in configs {
        config_client.remove_config(config_name, "example-group").await?;
    }

    // 注销服务
    naming_client.deregister_instance(service_name, "127.0.0.1", 8080).await?;

    println!("\n=== 示例完成 ===");

    // 关闭客户端
    client.close().await;

    Ok(())
}